package com.example.androidgzipdemo;

import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

public class MainActivity extends AppCompatActivity {

    private TextView htmlContentTv;
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String HTML_URL = "https://www.163.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findView();
        initView();
        initData();
    }

    private void findView() {
        htmlContentTv = findViewById(R.id.activity_main_html_content_tv);
    }

    private void initView() {

    }

    private void initData() {
        new FetchHtmlAt(this).execute();
    }

    public void setData(String htmlContent) {
        htmlContentTv.setText(htmlContent);
    }

    static class FetchHtmlAt extends AsyncTask {

        private WeakReference<Activity> mainActivityWeak;

        private FetchHtmlAt(Activity mainActivity) {
            this.mainActivityWeak = new WeakReference<>(mainActivity);
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            return getHtmlContent();
        }

        @Override
        protected void onPostExecute(Object o) {
            ((MainActivity) mainActivityWeak.get()).setData(String.valueOf(o));
        }
    }

    private static String getHtmlContent() {
        try {
            URL url = new URL(HTML_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setRequestProperty("Accept-Encoding", "gzip");
            int code = connection.getResponseCode();
            if (code == 200) {
                String contentEncoding = connection.getContentEncoding();
                if (contentEncoding != null && contentEncoding.equals("gzip")) {
                    return convertToString(new GZIPInputStream(connection.getInputStream()));
                } else {
                    return convertToString(connection.getInputStream());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String convertToString(InputStream inputStream) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            return new String(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String convertToString(GZIPInputStream gzipInputStream) {
        StringBuilder stringBuffer = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gzipInputStream));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                line = new String(line.getBytes("UTF-8"));
                stringBuffer.append(line);
            }
            bufferedReader.close();
            return stringBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
